import requests
import zlib
import json
import base64
import time


def addSalt(ori: bytearray):
    # 从网页JS当中提取到的混淆盐值，每隔一位做一次异或运算
    Salt = '%#54$^%&SDF^A*52#@7'
    i = 0
    for ch in ori:
        if i % 2 == 0:
            ch = ch ^ ord(Salt[(i // 2) % len(Salt)])
        ori[i] = ch
        i += 1
    return ori


def encodeData(ori: str):
    # 开头的数字是原始报文长度
    Length = len(ori)
    Message = str.encode(ori)
    # 首先用zlib进行压缩
    Compressed = bytearray(zlib.compress(Message))
    # 然后加盐混淆
    Salted = addSalt(Compressed)
    # 最后将结果转化为base64编码
    Result = base64.b64encode(Salted).decode('utf-8')
    # 将长度头和base64编码的报文组合起来
    return str(Length) + '$' + Result


def decodeData(ori: str):
    # 分离报文长度头
    # tbc: 增加报文头长度的验证
    Source = ori.split('$')[1]
    # base64解码
    B64back = bytearray(base64.b64decode(Source))
    # 重新进行加盐计算，恢复原始结果
    Decompressed = addSalt(B64back)
    # zlib解压
    Result = zlib.decompress(Decompressed).decode('utf-8')
    # 提取json
    return json.loads(Result)


header = {
    'Content-Type': 'application/json',
    'Origin': 'https://www.taoba.club',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Host': 'www.tao-ba.club',
    'Cookie': 'l10n=zh-cn',
    'User-Agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15',
    'Referer': 'https://www.taoba.club/',
    'Accept-Encoding': 'gzip, deflate, br',
    'Connection': 'keep-alive',
}
cookie = {
    'l10n': 'zh-cn',
}


def get_detail(ID):
    url = "https://www.taoba.club/idols/detail"
    now = int(time.time() * 1000)
    data = {"id": ID, "requestTime": now, "pf": "h5"}
    # print(data)
    data = encodeData(json.dumps(data))
    # print(data)
    response = requests.post(url=url,
                             headers=header,
                             data=data,
                             cookies=cookie)
    response = decodeData(response.text)
    return response


def get_ranking(ID):
    url = "https://www.taoba.club/idols/join/rank"
    now = int(time.time() * 1000)
    data = {
        "id": ID,
        "requestTime": now,
        "pf": "h5",
        'iscoopen': 0,
        '_version_': 1
    }
    # print(data)
    data = encodeData(json.dumps(data))
    # print(data)
    response = requests.post(url=url,
                             headers=header,
                             data=data,
                             cookies=cookie)
    response = decodeData(response.text)
    return response


def get_fund_info(ID):
    detail = get_detail(ID)
    raking = get_ranking(ID)
    return {
        "raised": detail['datas']['donation'],
        "backers": raking['juser'],
    }


if __name__ == "__main__":
    print(get_fund_info(6114))
